function [mode, objf, objgrd, user] = objfun(mode, n, w, objgrd, nstate,user)

    %%%%%%%%%%%%%%%%%%%%%%%
    % UNPACK USER STRUCTURE
    %%%%%%%%%%%%%%%%%%%%%%%

[SS,x1,x2,~,~,~,~,~,~,tau,gamma]=user_unpack(user);

    %%%%%%%%%%%%%%%%%%%%%%%
    % PREDICT SHAT AND RESIDUAL
    %%%%%%%%%%%%%%%%%%%%%%%

[shat,S,~,~]=predict_demand_share(x1,x2,w,user);
u=SS-shat;
    
    %%%%%%%%%%%%%%%%%%%%%%%
    % COMPUTE OBJECTIVE FUNCTION
    %%%%%%%%%%%%%%%%%%%%%%%
    
[check_f, check_fderiv] = check_fct_smooth(u,tau,gamma);
    
    %%%%%%%%%%%%%%%%%%%%%%%
    % COMPUTE DERIVATIVE
    %%%%%%%%%%%%%%%%%%%%%%%

d_u_d_beta = -S;

    %%%%%%%%%%%%%%%%%%%%%%%
    % PREPARE OUTPUT
    %%%%%%%%%%%%%%%%%%%%%%%

objf=check_f;
objgrd = check_fderiv*d_u_d_beta;

    %
